using System;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

namespace Tank
{
    /// <summary>
    /// Controls game states for switching between Menu Display, Game Mode, and Results Display
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {

        public enum GameState
        {
            MENU_DISPLAY,
            TITLE_SCREEN,
            START_GAME,
            IN_GAME,
            GAME_OVER,
            RESULTS_DISPLAY,
            SETUP_GAME
        }

        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        GameState gameState;
        Rectangle worldSize;
        Rectangle playableArea;
        Dictionary<string, Screen> gameScreens;
        List<Player> playerList;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            worldSize = new Rectangle(0, 0, 1280, 720);
            playableArea = new Rectangle(0,
                                         0 /*worldSize.Height - (int)(worldSize.Height * 0.9f)*/,
                                         worldSize.Width,
                                         worldSize.Height  /*(int)(worldSize.Height * 0.9f)*/);
            graphics.PreferredBackBufferWidth = worldSize.Width;
            graphics.PreferredBackBufferHeight = worldSize.Height;
            gameState = GameState.TITLE_SCREEN;
            this.IsMouseVisible = true;
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // Initialize the world instance
            World.Instance.InitWorld(playableArea, worldSize, spriteBatch);

            // Initialize Scenes
            InitScenes();

            base.Initialize();
        }

        // Creates new players from PlayerIndex list in SetUpScreen class
        // Called after SetUpScreen Transition to next screen
        private void AddActivePlayers()
        {
            playerList = new List<Player>();

            Debug.Assert(gameScreens["setUpScreen"].GetType() == Type.GetType("Tank.SetUpScreen"));
            playerList = ((SetUpScreen)gameScreens["setUpScreen"]).GetPlayerList();
        }


        private void InitScenes()
        {
            gameScreens = new Dictionary<string, Screen>();

            Screen titleScreen = new TitleScreen(worldSize.Width, worldSize.Height);
            titleScreen.AddTexture("Sky_01","Sky_01");
            titleScreen.AddTexture("Sky_02", "Sky_02");
            titleScreen.AddTexture("Sky_03", "Sky_03");
            titleScreen.AddTexture("Mountains_01", "Mountains_01");
            titleScreen.AddTexture("Mountains_02", "Mountains_02");
            titleScreen.AddTexture("Mountains_03", "Mountains_03");
            titleScreen.AddTexture("GrassLoop", "GrassLoop");
            titleScreen.AddTexture("GrassLoop_02", "GrassLoop");
            titleScreen.AddTexture("MainScreenTank", "MainScreenTank");
            titleScreen.AddTexture("TankdTitle", "TankdTitle");
            gameScreens.Add("titleScreen", titleScreen);
            
            

            Screen setUpScreen = new SetUpScreen(worldSize.Width, worldSize.Height);
            setUpScreen.AddTexture("background", "TestPickTankScreen");
            gameScreens.Add("setUpScreen", setUpScreen);

            Screen inGameScreen = new InGameScreen(worldSize.Width, worldSize.Height);
            //inGameScreen.AddTexture(World.Instance.CurrLevel.Surface.TextureID ); // TODO - needs to do this...
            inGameScreen.AddTexture("background", "TronBase");                                    // ... not this.
            gameScreens.Add("inGameScreen", inGameScreen);

            Screen postGameScreen = new PostGameScreen(worldSize.Width, worldSize.Height);
            postGameScreen.AddTexture("background", "TestPostGameScreen");
            gameScreens.Add("postGameScreen", postGameScreen);

        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            // TODO: use this.Content to load your game content here
            World.Instance.InitTextures(spriteBatch, Content);
            SoundManager.Instance.InitSounds(Content);
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Update the game based on what state the game is currently in
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            Input.Instance.Update();

            switch (gameState)
            {
                case GameState.MENU_DISPLAY:
                    {
                        break;
                    }
                case GameState.TITLE_SCREEN:
                    {
                        gameScreens["titleScreen"].Update((float)gameTime.ElapsedGameTime.TotalSeconds);
                        SoundManager.Instance.PlaySound(SoundType.SONG_TITLE);
                        if (gameScreens["titleScreen"].SceneOver)
                        {
                            gameState = GameState.SETUP_GAME;
                            gameScreens["titleScreen"].ResetScreen();
                        }
                        break;
                    }
                case GameState.SETUP_GAME:
                    {
                        gameScreens["setUpScreen"].Update((float)gameTime.ElapsedGameTime.TotalSeconds);
                        if (gameScreens["setUpScreen"].SceneOver)
                        {
                            AddActivePlayers();
                            World.Instance.ResetWorld();
                            World.Instance.SetPlayers( ((SetUpScreen)gameScreens["setUpScreen"]).GetPlayerList(),
                                                        ((SetUpScreen)gameScreens["setUpScreen"]).GetTankChoices());

                            // Call update on world so it updates sprite animations before they are draw for first time
                            
                            World.Instance.Update((float)gameTime.ElapsedGameTime.TotalSeconds);
							World.Instance.InitHUD(playerList);
                            gameState = GameState.IN_GAME;
                            gameScreens["setUpScreen"].ResetScreen();
                        }
                        break;
                    }
                case GameState.IN_GAME:
                    {
                        gameScreens["inGameScreen"].Update((float)gameTime.ElapsedGameTime.TotalSeconds);
                        World.Instance.Update((float)gameTime.ElapsedGameTime.TotalSeconds);
						World.Instance.Hud.Update();
                        if (gameScreens["inGameScreen"].SceneOver)
                        {
							SoundManager.Instance.StopSound(SoundType.SONG_TITLE);
                            gameState = GameState.RESULTS_DISPLAY;
                            gameScreens["inGameScreen"].ResetScreen();
                            World.Instance.currLevel.ResetLevel();      // ***TJS Reset level
                        }
                        break;
                    }
                case GameState.RESULTS_DISPLAY:
                    {
                        SoundManager.Instance.PlaySound(SoundType.SONG_RESULTS);
                        gameScreens["postGameScreen"].Update((float)gameTime.ElapsedGameTime.TotalSeconds);
                        if (gameScreens["postGameScreen"].SceneOver)
                        {
                            SoundManager.Instance.StopSound(SoundType.SONG_RESULTS);
                            gameState = GameState.TITLE_SCREEN;
                            gameScreens["postGameScreen"].ResetScreen();
                        }
                        break;
                    }
                case GameState.START_GAME:
                    {
                        break;
                    }
                case GameState.GAME_OVER:
                    {
                        break;
                    }


            }

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            // Draw out board
            spriteBatch.Begin(SpriteBlendMode.AlphaBlend);

            // TODO: Add your drawing code here
            switch (gameState)
            {
                case GameState.MENU_DISPLAY:
                    {
                        break;
                    }
                case GameState.TITLE_SCREEN:
                    {
                        gameScreens["titleScreen"].Draw(spriteBatch);
                        break;
                    }
                case GameState.START_GAME:
                    {
                        break;
                    }
                case GameState.IN_GAME:
                    {
                        // TODO - Add Level.Draw method call here
                        

                        gameScreens["inGameScreen"].Draw(spriteBatch);
                        World.Instance.Draw();
						World.Instance.Hud.Draw();
                        break;
                    }
                case GameState.GAME_OVER:
                    {
                        break;
                    }
                case GameState.RESULTS_DISPLAY:
                    {
                        gameScreens["postGameScreen"].Draw(spriteBatch);
                        break;
                    }
                case GameState.SETUP_GAME:
                    {
                        gameScreens["setUpScreen"].Draw(spriteBatch);
                        break;
                    }
            }

            // Draw out Sprites
            spriteBatch.End();

            base.Draw(gameTime);
        }
    }
}
